package meijuli.com.join51.business.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.jhx.common.utils.Constants;
import com.jhx.common.framework.QuickBaseActivity;
import com.jhx.common.model.Event;

import org.greenrobot.eventbus.EventBus;

/**
 *
 * @author wenqin 2017-07-14 16:05
 */

public class WebViewActivity extends QuickBaseActivity {
    public static final String KEY_URL = "key_url";
    public static final String KEY_SELECT = "key_select";
    public static final int CODE_CLOSE = 0x001;
    private WebView mWebView;
    private String mUrl;
    private int mSelect = 0;
    private String mTitle;

    public static void start(Context context, String url) {
        Intent intent = new Intent(context, WebViewActivity.class);
        intent.putExtra(KEY_URL, url);
        intent.getIntExtra(KEY_SELECT, 0);
        context.startActivity(intent);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        showToolbar();
        mWebView = new WebView(this);
        mUrl = getIntent().getStringExtra(KEY_URL);
        mSelect = getIntent().getIntExtra(KEY_SELECT, 0);
        mWebView.loadUrl(mUrl);
        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }
        });
        mWebView.setWebChromeClient(new WebChromeClient(){
            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                if(TextUtils.isEmpty(title)) {
                    setTitle(mTitle);
                } else {
                    setTitle(title);
                }
            }
        });

        this.setContentView(mWebView);
    }

    @Override
    public boolean onKeyDown(final int keyCode, final KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
            onGoBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void onGoBack() {
        if(mSelect == Constants.PayList.PAYMENT_QUICK_PAY) {
            Event event = new Event();
            event.setCode(CODE_CLOSE);
            EventBus.getDefault().post(event);
            finish();
        } else {
            if (mWebView.canGoBack()) {
                mWebView.goBack();
            } else {
                finish();
            }
        }
    }
}
